from django.shortcuts import render
from django.views import View
from meiduo_mall.libs.captcha.captcha import captcha
from django_redis import get_redis_connection
from . import constants
from django import http
from meiduo_mall.utils.response_code import RETCODE
import random
from meiduo_mall.libs.yuntongxun.sms import CCP
# Create your views here.
from celery_tasks.sms.tasks import send_sms


class ImageCodeView(View):
    def get(self,request,uuid):
        text,code,image=captcha.generate_captcha()
        redis_cli = get_redis_connection('image_code')
        redis_cli.setex(uuid,constants.IMAGE_CODE_EXPIRES,code )
        return http.HttpResponse(image,content_type='image/png')

class SmsCodeView(View):
    def get(self,request,mobile):

        uuid = request.GET.get('image_code_id')
        image_code = request.GET.get('image_code')
        redis_cli = get_redis_connection('sms_code')

        if redis_cli.get(mobile+'_flag')is not None:
            return http.JsonResponse({"code": RETCODE.SMSCODERR,'errmsg':'获取短信太频繁'})
        if not all([uuid,image_code]):
            return http.JsonResponse({"code":RETCODE.PARAMERR,'errmsg':'参数不完整'})

        redis_cli=get_redis_connection('image_code')
        image_code_redis = redis_cli.get(uuid)
        if image_code_redis is None:
            return http.JsonResponse({'code':RETCODE.IMAGECODEERR,'errmsg':'图形验证码已过期，点击换一个'})
        redis_cli.delete(uuid)
        if image_code_redis.decode().lower() != image_code.lower():
            return http.JsonResponse({'code':RETCODE.IMAGECODEERR,'errmsg':'图形验证码错误'})

        sms_code = '%06d' % random.randint(0,999999)

        #redis_cli.setex(mobile,constants.SMS_CODE_EXPIRES,sms_code)
        #redis_cli.setex(mobile+'_flag',constants.SMS_CODE_FLAG,1)

        redis_pl = redis_cli.pipeline()
        redis_pl.setex(mobile,constants.SMS_CODE_EXPIRES,sms_code)
        redis_pl.setex(mobile + '_flag', constants.SMS_CODE_FLAG, 1)
        redis_pl.execute()

        #ccp = CCP()
        #ccp.send_template_sms(mobile,[sms_code,constants.SMS_CODE_EXPIRES/60],1)
        #print(sms_code)

        send_sms.delay(mobile,sms_code)
        return http.JsonResponse({'code':RETCODE.OK,'errmsg':'OK'})